import React, { useEffect, useState } from "react";
import Router, { withRouter } from '@/router/renderRouter';
import { Table, message, Divider, Tag, Card, Modal, Select, Form, InputNumber, Input, Button, Radio, Spin, Popconfirm, Switch } from "antd";
import BreadcrumbBox from "@/components/Base/BreadcrumbBox";
import '../index.scss';

import { 
  merchantClassList,
  merchantClassUpdate,
  merchantClassSave,
  merchantClassDetele,
  merchantClassInfo,
} from '@/api/api'
let milCToken = {}

const MerchantCategory = (props) => {
  const [modalForm] = Form.useForm();
  const layout = { sm: 24, md: 12, lg: 12, xl: 7, xxl: 7 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 3, xxl: 3 };
  const labelCol = { sm: 24, md: 6, lg: 6, xl: 6 };
  const wrapperCol = { sm: 24, md: 18, lg: 18, xl: 18 };
  // 列表数据
  const [dataSource, setDataSource] = useState([]);
  const [id, setId] = useState(null);
  const [info, setInfo] = useState(null);
  //详情
  const [modalOpen, setModalOpen] = useState(false)
  const [modalLoading, setModalLoading] = useState(false)
  //商户分类
  const [merchantOptions, setMerchantOptions] = useState([]);
  
  // 面包屑
  const breadcrumbList = ['系统设置', '商户分类']
  const [loading, setLoading] = useState(false)
  // 表单头部
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text: any, row: any, index: number) => `${index + 1}`,
    },
    {
      title: '商户分类',
      dataIndex: 'className',
      key: 'className',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '类型备注',
      dataIndex: 'classRemark',
      key: 'classRemark',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '存款金额（累计）',
      dataIndex: 'amount',
      key: 'amount',
      align: 'center',
      render: (text, row, index) => `${row.minAmount}-${row.maxAmount}` || '--',
    },
    {
      title: '变更日期',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '商户默认分类',
      dataIndex: 'merchantDefault',
      key: 'merchantDefault',
      align: 'center',
      render: (text, row, index) => {
        return<>
          <Switch checked={text===0} onChange={(e)=>{changeStatus(e,row)}} />
        </>
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a
            onClick={() => {
              openModel(record.id)
            }}
          >编辑</a>
          <Divider type="vertical" />
          <Popconfirm
              title="确定删除？"
              onConfirm={() => {
                deleteFn(record)
              }}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
        </>;
      },
    }
  ];
  // 商户分类列表
  const getMerchantClassList = async () => {
    try {
      setLoading(true)
      let res = await merchantClassList()
      if(res.code === 0) {
        setDataSource(res.data || [])
        let arr = []
        res.data.forEach(item=>{
          arr.push({
            value: item.className,
            label: item.className,
          })
        })
        setMerchantOptions(arr)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  // 删除
  const deleteFn = async (data) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res = await merchantClassDetele({
        id: data.id
      }, milCToken)
      if(res.code === 0) {
        message.success('删除成功')
        getMerchantClassList()
      }
    } catch (error) {
      console.log(error)
    }
  }
  
  
  const changeStatus = async (status,data) => {
    try {
      setLoading(true)
      data.merchantDefault = status===true?0:1;
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res = await merchantClassUpdate({
        id: data.id,
        status: data.merchantDefault
      })
      if(res.code === 0) {
        message.success('操作成功')
        getMerchantClassList()
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  
  // 详情
  const openModel = async (data=null) => {
    try {
      setId(data);
      setInfo(null)
      modalForm.resetFields();
      setModalOpen(true);
      if(data){
        if (typeof milCToken.source === 'function') {
          milCToken.source('终止请求'); //取消请求
        }
        setModalLoading(true)
        let res = await merchantClassInfo({
          id: data
        }, milCToken)
        if(res.code === 0) {
          res.data.merchantDefault = res.data.merchantDefault===1?true:false
          setInfo(res.data)
          modalForm.setFieldsValue(res.data);
        }
        setModalLoading(false);
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 详情
  const saveDetail = async (data) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      setModalLoading(true)
      data.merchantDefault = data.merchantDefault===true?1:0
      let res = 
      id 
      ?
      await merchantClassUpdate({
        id,
        ...data,
      }, milCToken)
      :
      await merchantClassSave({
        ...data,
      }, milCToken)
      if(res.code === 0) {
        message.success('保存成功')
        getMerchantClassList()
      }
      setModalLoading(false)
      setModalOpen(false);
    } catch (error) {
      console.log(error)
    }
  }
  const handleOk = () => {
    setModalOpen(false);
  };
  const handleCancel = () => {
    setModalOpen(false);
  };
  // 更新
  useEffect(() => {
    // 获取列表
    getMerchantClassList()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <>
      <div className="system-component">
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className="system-main">
          <div className="table-box">
            <Card>
              <Button type="primary" onClick={()=>{openModel()}}>
                添加商户类型设置
              </Button>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1000 }}
                rowKey={'id'}
                className='antd-table'
                dataSource={dataSource}
                pagination={false}
                columns={columns} />
            </Card>
          </div>
        </div>
        
        <Modal title={id?'编辑币种':'新建币种'} visible={modalOpen} footer={null} onCancel={() => {
          setModalOpen(false)
          modalForm.resetFields()
        }}>
          <Spin spinning={modalLoading}>
            <Form
              form={modalForm}
              onFinish={(val) => {
                setInfo(val)
                saveDetail({
                  ...val
                });
              }}
            >
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="商户分类"
                name="className"
                rules={[{ required: true, message: '请选择商户分类' }]}
              >
                {/* <Select options={merchantOptions} /> */}
                <Input />
              </Form.Item>   
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="类型备注"
                name="classRemark"
                rules={[{ required: true, message: '请输入类型备注' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="最低存款金额"
                name="minAmount"
                rules={[{ required: true, message: '请输入最低存款金额' }]}
              >
                <InputNumber />
              </Form.Item>
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="最高存款金额"
                name="maxAmount"
                rules={[{ required: true, message: '请输入最高存款金额' }]}
              >
                <InputNumber />
              </Form.Item>
              <Form.Item
                labelCol={labelCol}
                wrapperCol={wrapperCol}
                label="商户默认分类"
                name="merchantDefault"
                valuePropName="checked"
                rules={[{ required: true, message: '请选择是否为商户默认分类' }]}
              >
                <Switch />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button className='reset-btn' type="default" htmlType="button" onClick={() => {
                  modalForm.setFieldsValue(info);
                }}>
                  重置
                </Button>
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      </div>
    </>
  )
}
export default withRouter(MerchantCategory)